#include <stdlib.h>
#include <string.h>
#include <cjson/cJSON.h>
#include "web.h"
#include "ccas/ccas.h"

int save_json_conf(char *filename) {
	//创建JSON对象
	cJSON *root = cJSON_CreateObject();

	// 添加字符串数据
	cJSON_AddStringToObject(root, "hostname", "");
	cJSON_AddStringToObject(root, "username", "");
	cJSON_AddStringToObject(root, "password", "");
	cJSON_AddStringToObject(root, "database", "");

	char *json_str = cJSON_Print(root);
	if (json_str == NULL) {
		fprintf(stderr, "Error createing JSON string\n");
		cJSON_Delete(root);
		return 1;
	}

	string s = ccas_rs(json_str);
	ccas_wf(s, filename);

	ccas_free(&s);
	free(json_str);
	cJSON_Delete(root);
	return 0;
}

int read_json_conf(char *filename, struct DatabaseKeygen *dk) {
	string s = ccas_rf(filename);
	char *json_str = ccas_ws(s);
	//printf("%s\n",json_str);

	cJSON *root = cJSON_Parse(json_str);
	if (root == NULL) {
		const char *error_ptr = cJSON_GetErrorPtr();
		if (error_ptr != NULL) {
			fprintf(stderr, "Error before: %s\n", error_ptr);
		}
		return 1;
	}

	cJSON *hostname = cJSON_GetObjectItem(root, "hostname");
	if (!cJSON_IsString(hostname) || hostname->valuestring == NULL) {
		cJSON_Delete(root);
		free(json_str);
		ccas_free(&s);
		return 1;
	}

	cJSON *username = cJSON_GetObjectItem(root, "username");
	if (!cJSON_IsString(username) || username->valuestring == NULL) {
		cJSON_Delete(root);
		free(json_str);
		ccas_free(&s);
		return 1;
	}

	cJSON *password = cJSON_GetObjectItem(root, "password");
	if (!cJSON_IsString(password) || password->valuestring == NULL) {
		cJSON_Delete(root);
		free(json_str);
		ccas_free(&s);
		return 1;
	}

	cJSON *database = cJSON_GetObjectItem(root, "database");
	if (!cJSON_IsString(database) || database->valuestring == NULL) {
		cJSON_Delete(root);
		free(json_str);
		ccas_free(&s);
		return 1;
	}

	dk->hostname = (char*)malloc(strlen(hostname->valuestring) + 1);
	strcpy(dk->hostname, hostname->valuestring);

	dk->username = (char*)malloc(strlen(username->valuestring) + 1);
	strcpy(dk->username, username->valuestring);

	dk->password = (char*)malloc(strlen(password->valuestring) + 1);
	strcpy(dk->password, password->valuestring);

	dk->database = (char*)malloc(strlen(database->valuestring) + 1);
	strcpy(dk->database, database->valuestring);

	cJSON_Delete(root);
	free(json_str);
	ccas_free(&s);
	return 0;
}

void release_json_conf(struct DatabaseKeygen *dk) {
	free(dk->hostname);
	free(dk->username);
	free(dk->password);
	free(dk->database);
}
